package com.ocm.tourism.core.util;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.ocm.tourism.core.domain.RoleType;
import com.ocm.tourism.core.exception.ServicePermissionRuntimeException;
import com.ocm.tourism.core.model.UserInfo;

public class UserUtil {

   public static UserInfo getAuthenticated() {
      SecurityContext securityContext = SecurityContextHolder.getContext();
      if (securityContext != null && securityContext.getAuthentication() != null) {
         Object principal = securityContext.getAuthentication().getPrincipal();
         if (principal instanceof UserDetails) {
            return (UserInfo) principal;
         }
      }
      return null;
   }

   public static boolean hasLogined(){
      UserInfo userInfo = getAuthenticated();
      if (userInfo == null)
         return false;
      return true;
   }

   @SuppressWarnings("unchecked")
   public static boolean hasRole(RoleType roleType){
      UserInfo userInfo = getAuthenticated();
      if (userInfo == null)
         return false;
      Collection<GrantedAuthority> grantedAuthorities = (Collection<GrantedAuthority>) userInfo.getAuthorities();
      for (Iterator<GrantedAuthority> it = grantedAuthorities.iterator(); it.hasNext();){
         GrantedAuthority grantedAuthority = it.next();
         if (grantedAuthority.getAuthority().equals(roleType.name())){
            return true;
         }
      }
      return false;
   }

   public static long currentParticipantId(){
      UserInfo userInfo = getAuthenticated();
      if (userInfo == null)
         throw new ServicePermissionRuntimeException("User have not loged-in yet");
      return userInfo.getParticipantId();
   }
}
